from google.appengine.ext import webapp
from google.appengine.api.urlfetch import fetch , GET , POST , DELETE
from com.blogspot.zizon.twitter.Oauth import quote , unquote
from com.blogspot.zizon.twitter.Oauth import Oauth
import base64
import logging

# proxy apis
class RestApiProxy(webapp.RequestHandler): 
    
    # overide this method to get proxied api server url
    def getApiServer(self):
        return "";
 
    # just forward request , replacing original host
    def proxy(self , method , *args):
        
        # do api proxy
        url = None
        auth = None
        contenttype = None
        ourheaders = {}
        try:
            url = self.request.headers["Zcreal-Nsurl"]
            if "twitter" in url:
                url = url.replace("twitter.aaa","twitter.com")                
        except:
            try:
                url1 = base64.b64decode(self.request.get("url"))
                url = base64.b64decode(url1)
                if url == "":
                    self.response.out.write("No, baby, no")
                    return                    
            except:
                self.response.out.write("No, baby, no")
                return
        try:
            auth = self.request.headers["Authorization"]
        except:
            auth = None

        logging.info("url: %s" % url)
        logging.info("request body: %s" % self.request.body)
        
        for key in self.request.headers.keys():
            logging.info(self.request.headers.get(key))
            ourheaders[key] = self.request.headers.get(key)
        
        logging.info(self.request.headers)
        response = fetch(
                            "%s" % (    url
                                        ),
                            self.request.body,
                            method,
                            ourheaders,
                        )
        self.response.headers = response.headers
        self.response.out.write(response.content)
        logging.info("response headers: %s, response content: %s", response.headers, response.content)

    # handle http get   
    def get(self, *args):
        # parameters = self.convertParameters(self.request.query_string)
        # # I don't need oauth
        # # self.prepareHeader("GET", parameters)
        # self.request.query_string = "&".join("%s=%s" % (quote(key) , quote(value)) for key, value in parameters.items())
        self.proxy(GET, *args)
        
    # handle http post
    def post(self, *args):
        # parameters = self.convertParameters(self.request.body)
        # # self.prepareHeader("POST", parameters)
        # self.request.body = "&".join("%s=%s" % (quote(key) , quote(value)) for key, value in parameters.items())
        self.proxy(POST, *args)
    
    # handle http delete   
    def delete(self , *arps):
        self.proxy(DELETE, *arps)
    
    # convert query strings to dictionary    
    def convertParameters(self, source):
        parameters = {}
        for pairs in source.split("&"):
            item = pairs.split("=")
            if len(item) == 2:
                parameters[item[0]] = unquote(item[1])
        return parameters